#!/bin/bash
# 数据库和文件恢复脚本

set -e

# 配置
BACKUP_DIR="/opt/backups"

# 从环境变量读取数据库配置（或直接修改）
DB_NAME="${DB_NAME:-nanchang_tour}"
DB_USER="${DB_USER:-nanchang_user}"
DB_PASSWORD="${DB_PASSWORD:-your_password}"
DB_HOST="${DB_HOST:-localhost}"

echo "=========================================="
echo "数据库恢复工具"
echo "=========================================="
echo ""

# 列出可用的备份文件
echo "可用的数据库备份:"
ls -lh $BACKUP_DIR/*.sql.gz 2>/dev/null | awk '{print NR, $9, $5}'

if [ $? -ne 0 ]; then
    echo "错误: 未找到备份文件"
    exit 1
fi

echo ""
read -p "请输入要恢复的备份文件编号: " file_num

# 获取选中的文件
backup_file=$(ls $BACKUP_DIR/*.sql.gz | sed -n "${file_num}p")

if [ -z "$backup_file" ]; then
    echo "错误: 无效的文件编号"
    exit 1
fi

echo ""
echo "选中的备份文件: $backup_file"
read -p "确认恢复？这将覆盖现有数据库！(yes/no): " confirm

if [ "$confirm" != "yes" ]; then
    echo "取消恢复"
    exit 0
fi

echo ""
echo "开始恢复数据库..."

# 解压备份文件
gunzip -c $backup_file > /tmp/restore.sql

# 恢复数据库
mysql -h $DB_HOST -u $DB_USER -p"$DB_PASSWORD" $DB_NAME < /tmp/restore.sql

# 清理临时文件
rm /tmp/restore.sql

echo ""
echo "=========================================="
echo "数据库恢复完成！"
echo "=========================================="

